var path = require('path');

var koa = require('koa');
var logger = require('koa-logger');
var bodyparser = require('koa-bodyparser');
var render = require('koa-ejs');
var route = require('./routes/');
var config = require('./config.json');

var exception = require('./lib/exception');
var log = require('./lib/logger');
var app = koa();
var koaBody = require('koa-body');
app.use(koaBody({multipart: true,formidable: {keepExtensions: true}}));

var session = require('koa-generic-session');
var redisStore = require('koa-redis');
app.keys = ['fangmm', 'T-brokers'];

render(app, {
    root: path.join(__dirname, 'views'),
    viewExt: 'ejs',
    layout: false,
    cache: false,
    debug: true
});
app.use(logger());

app.use(bodyparser());
//app.use(session({
//    store: redisStore({
//        host: config.redis.host,
//        port: config.redis.port,
//        db: config.redis.db,
//        ttl: 7000000
//    })
//}));
app.use(session());
//var serve = require('koa-static');
//app.use(serve(__dirname + '/public'));
var send = require('koa-send');
const resolve = require('path').resolve;
// 自定义静态资源地址
app.use(function *serve(next){
    yield* next;

    var opts = {};
    opts.root = resolve(__dirname + '/public');
    if (this.method != 'HEAD' && this.method != 'GET') return;
    if (this.body != null || this.status != 404) return;

    yield send(this, this.path.substring('/app/static'.length, this.path.length), opts);
});

app.use(function *(next) {
    try {
        this.session.test = "test";
        yield next;
    } catch (err) {
        switch (err.code) {
            // 捕捉自定义错误
            case exception.RequestError:
                this.redirect('/app/error');
                break;
            case exception.NotFound:
                this.redirect('/app/404');
                break;
            case exception.DBError:
            case exception.ServerError:
                this.redirect('/app/error');
                break;
            // 捕捉系统性错误
            default:
                console.log('system error: %s', err);
                log.http('system error: %s', err);
                this.redirect('/app/404');
        }
    }
});

app.use(route.routes())
    .use(route.allowedMethods());

var port = process.env.PORT || config.port;
app.listen(port, function () {
    log.http('listening on port %s\n' ,port);
});